/*
给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。

输入：head = [1,2,3,4,5]
输出：[5,4,3,2,1]

https://leetcode.cn/problems/reverse-linked-list/
 */

package LC0206;


class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    public void add(int num){
        ListNode list = new ListNode(num);

        if(this.next == null) {
            this.next = list;
        } else {
            this.next.add(num);
        }
    }

    public void print(){
        System.out.print(this.val);
        if (this.next != null) {
            System.out.print(",");
            this.next.print();
        }
    }
}

class Solution1 {
    public static void main(String[] args) {
        ListNode head = new ListNode();
        head.val = 1;
        head.add(2);
        head.add(3);
        head.add(4);
        head.add(5);

        head.print();

        Solution1 test = new Solution1();
        ListNode rev = test.reverseList(head);

        System.out.println(" ");
        rev.print();

    }

    // 链表 双指针 移动反转
    public ListNode reverseList(ListNode head) {
        ListNode left = null;
        ListNode right = head;
        while (right != null){
            ListNode temp = right.next;
            // 反转
            right.next = left;
            // 向右移动
            left = right;
            right = temp;
        }
        return left;
    }
}
